// Vhall Stream Saver - Options Page Script
// 下载管理器页面和设置管理

class VhallOptions {
  constructor() {
    this.currentTab = 'downloads';
    this.downloads = [];
    this.streams = [];
    this.settings = {};
    this.isExtensionEnv = typeof chrome !== 'undefined' && chrome.storage && chrome.runtime;
    this.init();
  }

  async init() {
    this.setupEventListeners();
    this.setupTabNavigation();
    await this.loadSettings();
    await this.loadData();
    this.checkNativeHost();
    this.setupMessageListener();
    // 非扩展环境下，模拟进度以便预览 UI
    if (!this.isExtensionEnv) {
      this.simulateProgressDemo();
    }
  }

  // 设置事件监听器
  setupEventListeners() {
    // Header actions
    document.getElementById('refreshBtn').addEventListener('click', () => {
      this.refreshData();
    });

    document.getElementById('settingsBtn').addEventListener('click', () => {
      this.switchTab('settings');
    });

    // Downloads tab actions
    document.getElementById('clearCompletedBtn').addEventListener('click', () => {
      this.clearCompletedDownloads();
    });

    document.getElementById('pauseAllBtn').addEventListener('click', () => {
      this.pauseAllDownloads();
    });

    // Streams tab actions
    document.getElementById('clearStreamsBtn').addEventListener('click', () => {
      this.clearAllStreams();
    });

    document.getElementById('exportStreamsBtn').addEventListener('click', () => {
      this.exportStreams();
    });

    // Settings actions
    document.getElementById('saveSettingsBtn').addEventListener('click', () => {
      this.saveSettings();
    });

    document.getElementById('resetSettingsBtn').addEventListener('click', () => {
      this.resetSettings();
    });

    document.getElementById('browseYtdlpBtn').addEventListener('click', () => {
      this.browseYtdlpPath();
    });

    document.getElementById('installYtdlpBtn').addEventListener('click', () => {
      this.installYtdlp();
    });

    document.getElementById('testYtdlpBtn').addEventListener('click', () => {
      this.testYtdlp();
    });
  }

  // 设置标签页导航
  setupTabNavigation() {
    document.querySelectorAll('.nav-item').forEach(item => {
      item.addEventListener('click', (e) => {
        e.preventDefault();
        const tabName = item.dataset.tab;
        this.switchTab(tabName);
      });
    });
  }

  // 切换标签页
  switchTab(tabName) {
    // 更新导航状态
    document.querySelectorAll('.nav-item').forEach(item => {
      item.classList.remove('active');
    });
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

    // 更新内容区域
    document.querySelectorAll('.tab-content').forEach(content => {
      content.classList.remove('active');
    });
    document.getElementById(`${tabName}Tab`).classList.add('active');

    this.currentTab = tabName;

    // 加载对应数据
    switch (tabName) {
    case 'downloads':
      this.renderDownloads();
      break;
    case 'streams':
      this.renderStreams();
      break;
    case 'settings':
      this.renderSettings();
      break;
    }
  }

  // 设置消息监听器
  setupMessageListener() {
    if (!this.isExtensionEnv || !chrome.runtime || !chrome.runtime.onMessage) return;
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      if (message.type === 'STREAM_DETECTED') {
        this.handleNewStream(message.data);
      } else if (message.type === 'DOWNLOAD_PROGRESS') {
        this.handleDownloadProgress(message.data);
      }
    });
  }

  // 加载设置
  async loadSettings() {
    try {
      const result = await this.getStorage().get(['vhallSettings']);
      this.settings = result.vhallSettings || this.getDefaultSettings();
    } catch (error) {
      console.error('[Options] Failed to load settings:', error);
      this.settings = this.getDefaultSettings();
    }
  }

  // 获取默认设置
  getDefaultSettings() {
    return {
      defaultQuality: 'best',
      downloadPath: '',
      autoDownload: false,
      ytdlpPath: '',
      ytdlpArgs: '--format best',
      enableLogging: false,
      enableNotifications: true,
      maxConcurrentDownloads: 3
    };
  }

  // 加载数据
  async loadData() {
    await Promise.all([
      this.loadDownloads(),
      this.loadStreams()
    ]);
  }

  // 加载下载任务
  async loadDownloads() {
    try {
      const result = await this.getStorage().get(['downloads']);
      this.downloads = result.downloads || [];
      this.renderDownloads();
    } catch (error) {
      console.error('[Options] Failed to load downloads:', error);
      this.downloads = [];
    }
  }

  // 加载流数据
  async loadStreams() {
    if (!this.isExtensionEnv) {
      this.streams = [];
      this.renderStreams();
      this.updateStreamCount();
      return;
    }
    try {
      const response = await this.sendMessage({ type: 'GET_DETECTED_STREAMS' });
      if (response.success) {
        this.streams = response.data;
        this.renderStreams();
        this.updateStreamCount();
      }
    } catch (error) {
      console.error('[Options] Failed to load streams:', error);
      this.streams = [];
    }
  }

  // 检查 Native Host 状态
  async checkNativeHost() {
    const statusElement = document.getElementById('ytdlpStatus');
    statusElement.textContent = '检查中...';
    statusElement.className = 'status-value checking';

    if (!this.isExtensionEnv) {
      statusElement.textContent = '不可用';
      statusElement.className = 'status-value unavailable';
      return;
    }

    try {
      const response = await this.sendMessage({ type: 'CHECK_NATIVE_HOST' });

      if (response.available) {
        statusElement.textContent = '可用';
        statusElement.className = 'status-value available';
      } else {
        statusElement.textContent = '不可用';
        statusElement.className = 'status-value unavailable';
      }
    } catch (error) {
      console.error('[Options] Failed to check native host:', error);
      statusElement.textContent = '不可用';
      statusElement.className = 'status-value unavailable';
    }
  }

  // 渲染下载任务
  renderDownloads() {
    const emptyState = document.getElementById('downloadsEmpty');
    const downloadsList = document.getElementById('downloadsList');

    if (this.downloads.length === 0) {
      emptyState.classList.remove('hidden');
      downloadsList.classList.add('hidden');
      return;
    }

    emptyState.classList.add('hidden');
    downloadsList.classList.remove('hidden');

    downloadsList.innerHTML = this.downloads.map(download => this.renderDownloadItem(download)).join('');
    this.bindDownloadActions();
  }

  // 渲染单个下载项目
  renderDownloadItem(download) {
    const progress = download.progress || 0;
    const status = download.status || 'pending';
    const statusText = this.getStatusText(status);
    const timeAgo = this.formatTimeAgo(download.created_at);

    return `
      <div class="download-item" data-download-id="${download.id}">
        <div class="item-header">
          <div class="item-info">
            <div class="item-title" title="${download.title}">
              ${this.escapeHtml(download.title)}
            </div>
            <div class="item-url" title="${download.url}">
              ${this.escapeHtml(download.url)}
            </div>
          </div>
          <div class="item-status">
            <span class="status-badge ${status}">${statusText}</span>
            <span class="text-muted">${timeAgo}</span>
          </div>
        </div>
        
        ${status === 'downloading' ? `
          <div class="progress-bar">
            <div class="progress-fill" style="width: ${progress}%"></div>
          </div>
        ` : ''}
        
        <div class="item-details">
          <span>质量: ${download.quality || '未知'}</span>
          <span>•</span>
          <span>方法: ${download.method || '未知'}</span>
          ${download.fileSize ? `<span>•</span><span>大小: ${this.formatFileSize(download.fileSize)}</span>` : ''}
          ${progress > 0 ? `<span>•</span><span>进度: ${progress.toFixed(1)}%</span>` : ''}
        </div>
        
        <div class="item-actions">
          ${status === 'downloading' ? `
            <button class="btn btn-secondary btn-small pause-btn" data-download-id="${download.id}">暂停</button>
          ` : status === 'paused' ? `
            <button class="btn btn-primary btn-small resume-btn" data-download-id="${download.id}">继续</button>
          ` : ''}
          
          ${status === 'completed' ? `
            <button class="btn btn-primary btn-small open-btn" data-download-id="${download.id}">打开</button>
          ` : ''}
          
          <button class="btn btn-secondary btn-small retry-btn" data-download-id="${download.id}">重试</button>
          <button class="btn btn-secondary btn-small remove-btn" data-download-id="${download.id}">移除</button>
        </div>
      </div>
    `;
  }

  // 渲染流列表
  renderStreams() {
    const emptyState = document.getElementById('streamsEmpty');
    const streamsList = document.getElementById('streamsList');

    if (this.streams.length === 0) {
      emptyState.classList.remove('hidden');
      streamsList.classList.add('hidden');
      return;
    }

    emptyState.classList.add('hidden');
    streamsList.classList.remove('hidden');

    streamsList.innerHTML = this.streams.map(stream => this.renderStreamItem(stream)).join('');
    this.bindStreamActions();
  }

  // 渲染单个流项目
  renderStreamItem(stream) {
    const qualities = this.extractQualities(stream.hls_domainnames);
    const timeAgo = this.formatTimeAgo(stream.detected_at);
    const hasLineOptions = stream.hls_options && Object.keys(stream.hls_options).length > 0;

    return `
      <div class="stream-item" data-stream-id="${stream.id}">
        <div class="item-header">
          <div class="item-info">
            <div class="item-title" title="${stream.video_title}">
              ${this.escapeHtml(stream.video_title)}
            </div>
            <div class="item-url" title="${stream.page_url}">
              ${this.escapeHtml(stream.page_url)}
            </div>
          </div>
          <div class="item-status">
            <span class="text-muted">${timeAgo}</span>
          </div>
        </div>

        <div class="item-details">
          <span>质量: ${qualities.join(', ')}</span>
          <span>•</span>
          <span>Token: ${stream.token ? '有效' : '无效'}</span>
          ${hasLineOptions ? '<span>•</span><span class="line-selector"><select class="line-select" data-stream-id="' + stream.id + '">' + this.generateLineOptions(stream.hls_options) + '</select></span>' : ''}
          <span>•</span>
          <span>来源: ${this.extractDomain(stream.page_url)}</span>
        </div>

        <div class="item-actions">
          <button class="btn btn-primary btn-small download-stream-btn" data-stream-id="${stream.id}">下载</button>
          <button class="btn btn-secondary btn-small copy-stream-btn" data-stream-id="${stream.id}">复制命令</button>
          <button class="btn btn-secondary btn-small remove-stream-btn" data-stream-id="${stream.id}">移除</button>
        </div>
      </div>
    `;
  }

  // 渲染设置
  renderSettings() {
    // 填充设置表单
    document.getElementById('defaultQuality').value = this.settings.defaultQuality;
    document.getElementById('downloadPath').value = this.settings.downloadPath;
    document.getElementById('autoDownload').checked = this.settings.autoDownload;
    document.getElementById('ytdlpPath').value = this.settings.ytdlpPath;
    document.getElementById('ytdlpArgs').value = this.settings.ytdlpArgs;
    document.getElementById('enableLogging').checked = this.settings.enableLogging;
    document.getElementById('enableNotifications').checked = this.settings.enableNotifications;
    document.getElementById('maxConcurrentDownloads').value = this.settings.maxConcurrentDownloads;
  }

  // 绑定下载操作
  bindDownloadActions() {
    // 暂停按钮
    document.querySelectorAll('.pause-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const downloadId = e.target.dataset.downloadId;
        this.pauseDownload(downloadId);
      });
    });

    // 继续按钮
    document.querySelectorAll('.resume-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const downloadId = e.target.dataset.downloadId;
        this.resumeDownload(downloadId);
      });
    });

    // 重试按钮
    document.querySelectorAll('.retry-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const downloadId = e.target.dataset.downloadId;
        this.retryDownload(downloadId);
      });
    });

    // 移除按钮
    document.querySelectorAll('.remove-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const downloadId = e.target.dataset.downloadId;
        this.removeDownload(downloadId);
      });
    });

    // 打开按钮
    document.querySelectorAll('.open-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const downloadId = e.target.dataset.downloadId;
        this.openDownload(downloadId);
      });
    });
  }

  // 生成线路选择选项
  generateLineOptions(hlsOptions) {
    if (!hlsOptions || Object.keys(hlsOptions).length === 0) {
      return '';
    }

    let options = '';
    const qualities = Object.keys(hlsOptions);

    if (qualities.length > 0) {
      const firstQuality = qualities[0];
      const lines = hlsOptions[firstQuality] || [];

      lines.forEach(line => {
        options += `<option value="${line.url}" data-quality="${firstQuality}">${line.line}</option>`;
      });
    }

    return options;
  }

  // 绑定流操作
  bindStreamActions() {
    // 线路选择器事件
    document.querySelectorAll('.line-select').forEach(select => {
      select.addEventListener('change', (e) => {
        const streamId = e.target.dataset.streamId;
        const selectedUrl = e.target.value;
        const selectedQuality = e.target.options[e.target.selectedIndex].dataset.quality;

        // 更新流的默认URL
        const stream = this.streams.find(s => s.id === streamId);
        if (stream) {
          stream.hls_domainnames[selectedQuality] = selectedUrl;
        }
      });
    });

    // 下载按钮
    document.querySelectorAll('.download-stream-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const streamId = e.target.dataset.streamId;
        this.downloadStream(streamId);
      });
    });

    // 复制命令按钮
    document.querySelectorAll('.copy-stream-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const streamId = e.target.dataset.streamId;
        this.copyStreamCommand(streamId);
      });
    });

    // 移除按钮
    document.querySelectorAll('.remove-stream-btn').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const streamId = e.target.dataset.streamId;
        this.removeStream(streamId);
      });
    });
  }

  // 下载流
  async downloadStream(streamId) {
    const stream = this.streams.find(s => s.id === streamId);
    if (!stream) return;

    try {
      // 创建下载任务
      const downloadTask = {
        id: this.generateId(),
        title: stream.video_title,
        url: this.selectBestQuality(stream.hls_domainnames)?.url,
        quality: this.selectBestQuality(stream.hls_domainnames)?.quality,
        referer: stream.referer,
        status: 'pending',
        progress: 0,
        created_at: new Date().toISOString(),
        method: 'unknown'
      };

      this.downloads.unshift(downloadTask);
      await this.saveDownloads();

      // 开始下载
      const response = await this.sendMessage({
        type: 'START_DOWNLOAD',
        data: {
          id: downloadTask.id,
          url: downloadTask.url,
          referer: downloadTask.referer,
          quality: downloadTask.quality,
          title: downloadTask.title,
          outputPath: this.generateOutputPath(downloadTask.title, downloadTask.quality)
        }
      });

      if (response.success) {
        downloadTask.status = 'downloading';
        downloadTask.method = response.method;
        await this.saveDownloads();
        this.renderDownloads();
        this.showToast('下载已开始', 'success');
      } else {
        downloadTask.status = 'failed';
        await this.saveDownloads();
        this.renderDownloads();
        this.showToast(`下载失败: ${response.error}`, 'error');
      }
    } catch (error) {
      console.error('[Options] Download failed:', error);
      this.showToast(`下载失败: ${error.message}`, 'error');
    }
  }

  // 保存设置
  async saveSettings() {
    try {
      // 收集设置数据
      this.settings = {
        defaultQuality: document.getElementById('defaultQuality').value,
        downloadPath: document.getElementById('downloadPath').value,
        autoDownload: document.getElementById('autoDownload').checked,
        ytdlpPath: document.getElementById('ytdlpPath').value,
        ytdlpArgs: document.getElementById('ytdlpArgs').value,
        enableLogging: document.getElementById('enableLogging').checked,
        enableNotifications: document.getElementById('enableNotifications').checked,
        maxConcurrentDownloads: parseInt(document.getElementById('maxConcurrentDownloads').value)
      };

      // 保存到存储
      await this.getStorage().set({ vhallSettings: this.settings });
      this.showToast('设置已保存', 'success');
    } catch (error) {
      console.error('[Options] Failed to save settings:', error);
      this.showToast('保存设置失败', 'error');
    }
  }

  // 重置设置
  async resetSettings() {
    if (confirm('确定要重置所有设置吗？')) {
      this.settings = this.getDefaultSettings();
      await this.getStorage().set({ vhallSettings: this.settings });
      this.renderSettings();
      this.showToast('设置已重置', 'success');
    }
  }

  // 安装 yt-dlp
  installYtdlp() {
    const instructions = `
安装 yt-dlp 说明：

Windows:
winget install yt-dlp

macOS:
brew install yt-dlp

Linux:
pip install yt-dlp

或者下载可执行文件：
https://github.com/yt-dlp/yt-dlp/releases

安装完成后，请重新测试连接。
    `;
    alert(instructions);
  }

  // 测试 yt-dlp
  async testYtdlp() {
    this.showToast('正在测试 yt-dlp 连接...', 'info');
    await this.checkNativeHost();
  }

  // 工具方法
  generateId() {
    return 'task_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }

  selectBestQuality(hlsDomainnames) {
    if (!hlsDomainnames || typeof hlsDomainnames !== 'object') {
      return null;
    }

    const priorities = ['1080p', '720p', '480p'];
    for (const quality of priorities) {
      if (hlsDomainnames[quality]) {
        return { quality, url: hlsDomainnames[quality] };
      }
    }

    const firstKey = Object.keys(hlsDomainnames)[0];
    if (firstKey) {
      return { quality: firstKey, url: hlsDomainnames[firstKey] };
    }

    return null;
  }

  generateOutputPath(title, quality) {
    const safeTitle = title.replace(/[^\w\s-]/g, '').replace(/\s+/g, '_');
    return `${safeTitle}_${quality}.%(ext)s`;
  }

  extractQualities(hlsDomainnames) {
    if (!hlsDomainnames || typeof hlsDomainnames !== 'object') {
      return ['未知'];
    }
    return Object.keys(hlsDomainnames);
  }

  extractDomain(url) {
    try {
      return new URL(url).hostname;
    } catch {
      return '未知';
    }
  }

  getStatusText(status) {
    const statusMap = {
      pending: '等待中',
      downloading: '下载中',
      completed: '已完成',
      failed: '失败',
      paused: '已暂停'
    };
    return statusMap[status] || status;
  }

  formatTimeAgo(dateString) {
    const now = new Date();
    const date = new Date(dateString);
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);

    if (diffMins < 1) return '刚刚';
    if (diffMins < 60) return `${diffMins}分钟前`;
    if (diffHours < 24) return `${diffHours}小时前`;
    return date.toLocaleDateString();
  }

  formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  updateStreamCount() {
    document.getElementById('streamCount').textContent = this.streams.length;
  }

  async saveDownloads() {
    await this.getStorage().set({ downloads: this.downloads });
  }

  // 刷新数据
  async refreshData() {
    await this.loadData();
    await this.checkNativeHost();
    this.showToast('数据已刷新', 'success');
  }

  // 清空所有流
  async clearAllStreams() {
    if (confirm('确定要清空所有检测到的流吗？')) {
      try {
        const response = await this.sendMessage({ type: 'CLEAR_DETECTED_STREAMS' });
        if (response.success) {
          this.streams = [];
          this.renderStreams();
          this.updateStreamCount();
          this.showToast('流列表已清空', 'success');
        }
      } catch (error) {
        console.error('[Options] Failed to clear streams:', error);
        this.showToast('清空失败', 'error');
      }
    }
  }

  // 导出流列表
  exportStreams() {
    if (this.streams.length === 0) {
      this.showToast('没有可导出的流', 'warning');
      return;
    }

    const data = this.streams.map(stream => ({
      title: stream.video_title,
      url: stream.page_url,
      qualities: this.extractQualities(stream.hls_domainnames),
      detected_at: stream.detected_at
    }));

    const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `vhall_streams_${new Date().toISOString().split('T')[0]}.json`;
    a.click();
    URL.revokeObjectURL(url);

    this.showToast('流列表已导出', 'success');
  }

  // 发送消息到 background
  sendMessage(message) {
    if (!this.isExtensionEnv) {
      return Promise.resolve(this.mockMessageResponse(message));
    }
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage(message, (response) => {
        if (chrome.runtime.lastError) {
          reject(new Error(chrome.runtime.lastError.message));
        } else {
          resolve(response);
        }
      });
    });
  }

  mockMessageResponse(message) {
    switch (message.type) {
    case 'GET_DETECTED_STREAMS':
      return { success: true, data: [] };
    case 'CHECK_NATIVE_HOST':
      return { available: false };
    case 'START_DOWNLOAD':
      return { success: true, method: 'hls' };
    case 'CLEAR_DETECTED_STREAMS':
      return { success: true };
    default:
      return { success: false, error: 'mock: unsupported' };
    }
  }

  // 显示提示消息
  showToast(message, type = 'info') {
    const container = document.getElementById('toastContainer');
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;

    toast.innerHTML = `
      <div class="toast-message">${this.escapeHtml(message)}</div>
      <button class="toast-close">×</button>
    `;

    toast.querySelector('.toast-close').addEventListener('click', () => {
      toast.remove();
    });

    container.appendChild(toast);

    setTimeout(() => {
      if (toast.parentNode) {
        toast.remove();
      }
    }, 5000);
  }

  // HTML 转义
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  // 处理新流
  handleNewStream(streamData) {
    // 检查是否已存在相同的流（基于 referer 和 token）
    const exists = this.streams.some(s => {
      // 如果 referer 相同，认为是同一个流
      if (s.page_url === streamData.page_url) {
        // 更新现有流的时间戳而不是显示新提示
        s.detected_at = streamData.detected_at;
        // 如果有新的 HLS 信息，也更新
        if (streamData.hls_domainnames && Object.keys(streamData.hls_domainnames).length > 0) {
          s.hls_domainnames = streamData.hls_domainnames;
        }
        if (this.currentTab === 'streams') {
          this.renderStreams();
        }
        return true;
      }
      return false;
    });

    if (!exists) {
      this.streams.unshift(streamData);
      if (this.currentTab === 'streams') {
        this.renderStreams();
      }
      this.updateStreamCount();
    }
  }

  // 处理下载进度
  handleDownloadProgress(progressData) {
    const download = this.downloads.find(d => d.id === progressData.downloadId);
    if (download) {
      if (typeof progressData.progress === 'number') {
        download.progress = progressData.progress;
      }
      if (progressData.status) {
        download.status = progressData.status;
      }
      if (typeof progressData.totalSize === 'number') {
        download.fileSize = progressData.totalSize;
      }
      // 持久化更新，确保刷新后保留进度和状态
      this.saveDownloads().catch(() => {});
      if (this.currentTab === 'downloads') {
        this.renderDownloads();
      }
    }
  }

  // 下载操作方法（占位符）
  async pauseDownload(downloadId) {
    this.showToast('暂停功能开发中', 'warning');
  }

  async resumeDownload(downloadId) {
    this.showToast('继续功能开发中', 'warning');
  }

  async retryDownload(downloadId) {
    this.showToast('重试功能开发中', 'warning');
  }

  async removeDownload(downloadId) {
    if (confirm('确定要移除这个下载任务吗？')) {
      this.downloads = this.downloads.filter(d => d.id !== downloadId);
      await this.saveDownloads();
      this.renderDownloads();
      this.showToast('下载任务已移除', 'success');
    }
  }

  async openDownload(downloadId) {
    this.showToast('打开功能开发中', 'warning');
  }

  async clearCompletedDownloads() {
    if (confirm('确定要清除所有已完成的下载任务吗？')) {
      this.downloads = this.downloads.filter(d => d.status !== 'completed');
      await this.saveDownloads();
      this.renderDownloads();
      this.showToast('已完成的下载任务已清除', 'success');
    }
  }

  async pauseAllDownloads() {
    this.showToast('暂停全部功能开发中', 'warning');
  }

  async copyStreamCommand(streamId) {
    const stream = this.streams.find(s => s.id === streamId);
    if (!stream) return;

    const bestQuality = this.selectBestQuality(stream.hls_domainnames);
    if (!bestQuality) {
      this.showToast('未找到可用的视频流', 'error');
      return;
    }

    const command = `yt-dlp "${bestQuality.url}" --referer "${stream.referer}" -o "${stream.video_title.replace(/[^\w\s-]/g, '').replace(/\s+/g, '_')}.%(ext)s"`;

    try {
      await navigator.clipboard.writeText(command);
      this.showToast('下载命令已复制到剪贴板', 'success');
    } catch (error) {
      console.error('[Options] Failed to copy command:', error);
      this.showToast('复制失败', 'error');
    }
  }

  async removeStream(streamId) {
    if (confirm('确定要移除这个流吗？')) {
      this.streams = this.streams.filter(s => s.id !== streamId);
      // 注意：这里只是从本地移除，实际应该通过 background 脚本同步
      this.renderStreams();
      this.updateStreamCount();
      this.showToast('流已移除', 'success');
    }
  }

  browseYtdlpPath() {
    this.showToast('请手动输入 yt-dlp 路径', 'info');
  }

  // 在非扩展环境下模拟一个简单进度，用于 UI 预览
  simulateProgressDemo() {
    if (this.isExtensionEnv) return;
    if (!this.downloads || this.downloads.length === 0) {
      const demo = {
        id: this.generateId(),
        title: '示例视频',
        url: 'https://example.com/video.m3u8',
        quality: '720p',
        status: 'downloading',
        progress: 0,
        created_at: new Date().toISOString(),
        method: 'hls'
      };
      this.downloads.unshift(demo);
      this.renderDownloads();
    }
    const id = this.downloads[0].id;
    let p = 0;
    const timer = setInterval(() => {
      p += 25;
      this.handleDownloadProgress({
        downloadId: id,
        status: p < 100 ? 'downloading' : 'completed',
        progress: Math.min(p, 100),
        totalSize: 12_345_678
      });
      if (p >= 100) {
        clearInterval(timer);
      }
    }, 600);
  }

  // 存储封装：扩展环境使用 chrome.storage，预览使用 localStorage
  getStorage() {
    if (this.isExtensionEnv && chrome.storage && chrome.storage.local) {
      return {
        get: (keys) => chrome.storage.local.get(keys),
        set: (obj) => chrome.storage.local.set(obj)
      };
    }
    return {
      async get(keys) {
        const result = {};
        keys.forEach(k => {
          const raw = localStorage.getItem(k);
          result[k] = raw ? JSON.parse(raw) : undefined;
        });
        return result;
      },
      async set(obj) {
        Object.keys(obj).forEach(k => {
          localStorage.setItem(k, JSON.stringify(obj[k]));
        });
      }
    };
  }
}

// 初始化 Options 页面
document.addEventListener('DOMContentLoaded', () => {
  new VhallOptions();
});
